<?php

namespace app\organization\controller\organization;

use app\common\controller\Frontend;
use app\common\model\banxi\organization\OrganizationQuotaApply as organizationQuotaApplyModel;
use app\common\service\organization\OrganizationQuotaService;
use ba\Exception;
use think\db\exception\DbException;
use think\db\exception\PDOException;
use think\exception\ValidateException;

/**
 * 机构
 */
class OrganizationQuotaApply extends Frontend
{
    protected array $noNeedLogin = [];

    protected array $noNeedPermission = ['*'];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new organizationQuotaApplyModel();
    }

    /**
     * 分页查询
     * @return void
     * @throws DbException
     */
    public function listPage(): void
    {
        $param = $this->request->param(['index', 'limit', 'orderBy', "query"]);
        $organizationId = $this->auth->organizationId;
        $param['query']['EQ_organizationId'] = $organizationId;
        //查询条件解析
        $where = get_query($param);
        //获取分页数据
        $pageParams = get_page_params($param);
        $list = $this->model->getListPage($where, $pageParams['page'], $pageParams['limit']);
        $this->ok('操作成功', result_row($list));
    }


    /**
     * 查询
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get()
    {
        $param = $this->request->param(["query" => []]);
        if (empty($param['query'])) {
            $this->fail('查询条件不能为空');
        }
        $where = get_query($param);
        $info = $this->model->getInfo($where);
        if (empty($info)) {
            $this->fail('记录不存在');
        }
        $this->ok('操作成功', $info);
    }


    /**
     * 名额申请
     * @return void
     */
    public function applyQuota()
    {
        $param = $this->request->param();
        try {
            $organizationId = $this->auth->organizationId;
            $organizationService = new OrganizationQuotaService();
            $res = $organizationService->applyQuota($organizationId, $param);
            if (!$res) throw new ValidateException($organizationService->getError());
        } catch (Exception|PDOException|ValidateException $e) {
            $this->fail($e->getMessage());
        }
        $this->ok('操作成功');
    }

}